<?php
/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Open Software License (OSL 3.0)
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/osl-3.0.php
 *
 * @author : $Id$
 */
class Cellphonezone_Trackingnumber_Model_Observer 
{	    
    public function deleteTrackingAfter(Varien_Event_Observer $observer)
    {
    	$track = $observer->getEvent()->getTrack();    	   
    	if ($track)
    	{
    		$orderId = $track->getOrderId(); 
	    	// Load the collection
	         $collection = Mage::getResourceModel('sales/order_shipment_grid_collection')->addFieldToFilter('order_id',$orderId);
	    	
	         $shipmentCol = $collection ->load();
	         
	         if ($shipmentCol)
	         {
	            foreach ($shipmentCol as $shipment)
		         {
		         	$shipmentTracking = explode("<br/>",$shipment->getTracking());
		         	if (!empty($shipmentTracking))
		         	{
		         		foreach ($shipmentTracking as $index=>$tracking)
		         		{
		         			if ($tracking == $track->getNumber())
		         			{
		         				unset($shipmentTracking[$index]);
		         			}
		         		}
		         	}
		         	else 
		         	{
		         		return;
		         	}
		         	$newTracking = implode("<br/>", $shipmentTracking);
		         	$shipment->setTracking($newTracking);
		         	$shipment->save();		         	
		         }
	         }
	         else 
	         {
	         	return;
	         }	         	         
    	}
    }
    
    public function saveTrackingAfter(Varien_Event_Observer $observer)
    {
    	$shipment = $observer->getEvent()->getShipment();
    	$trackCol = $shipment->getTracksCollection();    	
    	if (!$trackCol)
    	{
    		return '';
    	}
    	$trackings = array();
    	if ($trackCol)
    	{
    		foreach ($trackCol as $trackObj)
    		{
    			$trackings[] = $trackObj->getNumber();
    		}
    	}
    	$shipment->setTracking(implode("<br/>", $trackings));     	
    }
    
}
